package com.hw.one.collect.ocec.collect;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import java.util.stream.Collectors;

import org.apache.log4j.Logger;

import com.hw.one.collect.entity.CommonData;
import com.hw.one.collect.entity.DataCollector;
import com.hw.one.collect.entity.DataTypeEnum;
import com.hw.one.collect.ocec.entity.Ocec;
import com.hw.one.collect.ocec.util.CsvUtil;
import com.hw.one.collect.ocec.util.OcecUtil;
import com.hw.one.transpot.UploadDataUtil;

/**
 * @Class CsvDefaultDataCollector
 * @Author guoshenzhen
 * @Date 2018/3/14 13:16
 */
public class CsvDefaultDataCollector implements DataCollector<CommonData> {
	private Logger log = Logger.getLogger(this.getClass());

	@SuppressWarnings("finally")
	@Override
	public CommonData collect(String dateTime) {
		CommonData commonData = new CommonData(DataTypeEnum.OCEC);
		try {
			String filePathParam = dateTime.substring(0, 8);
			String filePath = OcecUtil.getLatestFilePath(filePathParam);
			List<String> strList = CsvUtil.parse(filePath);
			if (null == strList || strList.isEmpty()) {
				commonData = null;
			} else {
				List<String> collect = strList.stream().filter(item -> {
					if (null == item) {
						return false;
					}
					String[] split = item.split("\\s*,\\s*");
					return null != split && split.length >= 8 && !split[6].contains("Start") && converDateTime(split[6]).equals(dateTime);
				}).collect(Collectors.toList());
				
				if (null == collect || collect.size() == 0) {
					commonData = null;
				} else {
					String[] split = collect.get(collect.size() - 1).split("\\s*,\\s*");
					Ocec data = new Ocec();
					data.setOCugCSTPm(split[1]);
					data.setECugCSTPm(split[2]);
					data.setOCdiffugCSTPm(split[3]);
					data.setBCugCSTPm(split[4]);
					data.setTCugCSTPm(split[5]);
					data.setStartDateTime(format(split[6]));
					data.setMidtimeofCollection(format(split[7]));
					commonData.setList(new ArrayList<>(Arrays.asList(data)));
				}
			}
		} catch (Exception e) {
			commonData = null;
			log.error(e.getMessage());
		} finally {
			return commonData;
		}
	}

	private String format(String primitiveTime) {
		try {
			SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss a", Locale.ENGLISH);
			SimpleDateFormat ymdh = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			return ymdh.format(sdf.parse(primitiveTime));
		} catch (Exception e) {
			
		}
		return null;
	}
	
	private String converDateTime(String primitiveTime) {
		try {
			SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss a", Locale.ENGLISH);
			SimpleDateFormat ymdh = new SimpleDateFormat("yyyyMMddHH");
			return ymdh.format(sdf.parse(primitiveTime));
		} catch (Exception e) {
			
		}
		return null;
	}
	
	public static void main(String[] args) throws Exception {
		CsvDefaultDataCollector c = new CsvDefaultDataCollector();
		c.collect("2018121510");
	}
}
